package cn.accjiyun.controller.society;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.common.utils.WebUtils;
import cn.accjiyun.entity.society.SocietyUser;
import cn.accjiyun.entity.system.SystemUser;
import cn.accjiyun.service.society.RelativeService;
import cn.accjiyun.service.society.SocietyUserService;
import cn.accjiyun.service.system.SystemUserService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/2.
 */
@Controller
@RequestMapping("/admin/society")
public class AdminSocietyUserController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(AdminSocietyUserController.class);

    private static String addSocietyUser = getViewPath("/admin/society/society-user-add");
    private static String societyUserListPage = getViewPath("/admin/society/society-user-list");

    @Autowired
    private SocietyUserService societyUserService;
    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private RelativeService relativeService;

    @InitBinder({"societyUser"})
    public void initBinderSocietyUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("societyUser.");
    }

    /**
     * 创建用户
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/createSocietyUser")
    @ResponseBody
    public String createSocietyUser(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String username = request.getParameter("username");
            String roleName = request.getParameter("roleName");
            String identityCard = request.getParameter("identityCard");
            String sex = request.getParameter("sex");
            String nation = request.getParameter("nation");
            String mobile = request.getParameter("mobile");
            String email = request.getParameter("email");
            String address = request.getParameter("address");
            String joinDate = request.getParameter("joinDate");
            String insureEndDate = request.getParameter("insureEndDate");
            String comments = request.getParameter("comments");

            SocietyUser societyUser = new SocietyUser();
            societyUser.setUsername(username);
            societyUser.setSocietyRoleByRoleTypeId(societyUserService.querySocietyRoleIdByName(roleName));
            societyUser.setIdentityCard(identityCard);
            societyUser.setSex(sex);
            societyUser.setNation(nation);
            societyUser.setMobile(mobile);
            societyUser.setEmail(email);
            societyUser.setAddress(address);
            societyUser.setJoinDate(WebUtils.stringToTimestamp(joinDate));
            societyUser.setInsureEndDate(WebUtils.stringToTimestamp(insureEndDate));
            societyUser.setComments(comments);
            if (!societyUserService.validateIDCard(identityCard)) {
                resultJson.addProperty("status", 200);
                resultJson.addProperty("msg", "身份证已存在！");
                return gson.toJson(resultJson);
            }
            societyUserService.createSocietyUser(societyUser);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/society/userList");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.createSysUser()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] userIdsString = request.getParameter("userId").split(",");
            int[] userIds = new int[userIdsString.length];
            for (int i = 0; i < userIdsString.length; i++) {
                userIds[i] = Integer.valueOf(userIdsString[i]);
            }
            if (userIdsString != null && userIdsString.length > 0) {
                systemUserService.deleteSystemUser(userIds);
                societyUserService.deleteSocietyUser(userIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getUserList")
    @ResponseBody
    public String getUserList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map eqParams = new HashMap();
            Map likeStrings = new HashMap();
            queryEntity.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryEntity.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            queryEntity.setDateKeyword("joinDate");
            String roleName = request.getParameter("roleName");
            if (WebUtils.isValidateRealString(roleName)) {
                eqParams.put("societyRoleByRoleTypeId.roleTypeId",
                        societyUserService.querySocietyRoleIdByName(roleName).getRoleTypeId());
            }
            likeStrings.put("username", request.getParameter("keyword"));
            likeStrings.put("identityCard", request.getParameter("keyword"));
            queryEntity.setEqParams(eqParams);
            queryEntity.setLikeStrings(likeStrings);
            PageModel<SocietyUser> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<SocietyUser> societyUserList = societyUserService.querySocietyUserPage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (SocietyUser user : societyUserList) {
                JsonObject list = new JsonObject();
                list.addProperty("userId", user.getUserId());
                list.addProperty("username", user.getUsername());
                list.addProperty("roleName", user.getSocietyRoleByRoleTypeId().getRoleName());
                list.addProperty("identityCard", user.getIdentityCard());
                list.addProperty("sex", user.getSex());
                list.addProperty("nation", user.getNation());
                list.addProperty("mobile", user.getMobile());
                list.addProperty("email", user.getEmail());
                list.addProperty("address", user.getAddress());
                list.addProperty("joinDate", WebUtils.timestampToString(user.getJoinDate()));
                list.addProperty("insureEndDate", WebUtils.timestampToString(user.getInsureEndDate()));
                list.addProperty("comments", user.getComments());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminSocietyUser.getUserList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String userIdString = request.getParameter("userId");
            if (!WebUtils.isValidateRealString(userIdString) || !WebUtils.isNumeric(userIdString)) {
                resultJson.addProperty("status", 400);
                resultJson.addProperty("msg", "数据输入不合法！");
                return gson.toJson(resultJson);
            }
            String username = request.getParameter("username");
            String roleName = request.getParameter("roleName");
            String identityCard = request.getParameter("identityCard");
            String sex = request.getParameter("sex");
            String nation = request.getParameter("nation");
            String mobile = request.getParameter("mobile");
            String email = request.getParameter("email");
            String address = request.getParameter("address");
            String joinDate = request.getParameter("joinDate");
            String insureEndDate = request.getParameter("insureEndDate");
            String comments = request.getParameter("comments");

            SocietyUser societyUser = societyUserService.querySocietyUserById(Integer.valueOf(userIdString));
            societyUser.setUsername(username);
            societyUser.setSocietyRoleByRoleTypeId(societyUserService.querySocietyRoleIdByName(roleName));
            societyUser.setIdentityCard(identityCard);
            societyUser.setSex(sex);
            societyUser.setNation(nation);
            societyUser.setMobile(mobile);
            societyUser.setEmail(email);
            societyUser.setAddress(address);
            societyUser.setJoinDate(WebUtils.stringToTimestamp(joinDate));
            societyUser.setInsureEndDate(WebUtils.stringToTimestamp(insureEndDate));
            societyUser.setComments(comments);
            societyUserService.updateSocietyUser(societyUser);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminSocietyUser.update()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/userAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("roleNameList", societyUserService.queryAllSocietyRoleName());
        model.setViewName(addSocietyUser);
        return model;
    }

    @RequestMapping("/userList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("roleNameList", societyUserService.queryAllSocietyRoleName());
        model.setViewName(societyUserListPage);
        return model;
    }

}
